import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';

const { user, organization } = window.FORCE;
const userOwnData = [
  {
    id: user.id,
  },
];
const userOwnDataID = userOwnData.map((item) => item.id);

const ns = NameSpace('index');
export const RECEIVE_DATA = ns('RECEIVE_DATA');
export const RECEIVE_TOTAL_DATA = ns('RECEIVE_TOTAL_DATA');
export const SET_NAV_KEY = ns('SET_NAV_KEY');
export const SET_TAB_KEY = ns('SET_TAB_KEY');
export const SET_ORDER_KEY = ns('SET_ORDER_KEY');
export const SET_SEARCH = ns('SET_SEARCH');
export const SET_SEARCH_VALUE = ns('SET_SEARCH_VALUE');
export const SET_ADVANCEDSEARCHDATA = ns('SET_ADVANCEDSEARCHDATA');
export const SET_RESET_LIST = ns('SET_RESET_LIST');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');
export const COVER_LIST_DATA = ns('COVER_LIST_DATA');
export const GET_IP_WHITE = ns('GET_IP_WHITE');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData(data) {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
      data,
    });
  };
}
//
export function getMergeRequests(page, per_page) {
  return (dispatch, getState) => {
    const states = getState().organization.mergeRequests;
    const { tabKey: state, search, orderKey: order_by, searchValue } = states;
    // const { project_ids } = states.advancedSearchData;
    let searchData = {};
    if (searchValue === 'created') {
      searchData = {
        project_ids: null,
        author_tb_ids: userOwnDataID.join(','),
        assignee_tb_ids: null,
      };
    } else if (!searchValue) {
      searchData = {
        project_ids: null,
        author_tb_ids: null,
        assignee_tb_ids: null,
      };
    } else {
      try {
        const searchFormData = JSON.parse(searchValue);
        const { authorData, assigneeData, repoData } = searchFormData;
        searchData = {
          project_ids: repoData.length ? repoData.map((v) => v.value).join(',') : null,
          author_tb_ids: authorData.length
            ? authorData.map((item) => item._userId).join(',')
            : null,
          assignee_tb_ids: assigneeData.length
            ? assigneeData.map((item) => item._userId).join(',')
            : null,
        };
      } catch (err) {
        console.error(err);
      }
    }

    const formData = {
      page,
      state,
      search,
      order_by,
      per_page,
      ...searchData,
    };

    dispatch(requestAndgetData(formData));
  };
}

export function getAdvancedData(page, per_page) {
  return (dispatch, getState) => {
    dispatch({
      type: SET_RESET_LIST,
    });

    const states = getState().organization.mergeRequests;
    const { orderKey: order_by } = states;
    const search = null;

    const formData = {
      page,
      search,
      order_by,
      per_page,
      ...states.advancedSearchData,
    };

    dispatch(requestAndgetData(formData));
  };
}

export function requestAndgetData(formData) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'mr.advanced_search',
        data: {
          per_page: 10,
          ...formData,
        },
      })
      .then((list) => {
        // 如果是加载第一页，接收数据之前清理一遍数据，防止存在之前的慢请求返回的数据
        if (formData.page === 1) {
          dispatch({
            type: SET_RESET_LIST,
          });
        }
        list.shift();
        dispatch({
          type: RECEIVE_DATA,
          data: Object.assign(list, {
            currentPage: formData.page,
          }),
        });
        dispatch(getWebIdeLimet(list));
      })
      .fail(console.log);
    dispatch(getTotalData(formData));
  };
}

const getWebIdeLimet = (list) => {
  return async (dispatch, getState) => {
    const value = getState().organization.mergeRequests.mergeRequests;
    if (!list || list.length === 0) return false;
    // 过滤首页mr列表
    // 不重复的target_project_id
    const temp = {};
    const resources = list.reduce((prev, curv) => {
      // eslint-disable-next-line no-empty
      if (temp[curv.target_project_id]) {
      } else {
        temp[curv.target_project_id] = true;
        prev.push(curv);
      }
      return prev;
    }, []);
    // 过滤state内不重复的已经存在projectCloneDownload的target_project_id
    const cloneArray = resources.filter((va) => {
      const flag = value.find((val) => {
        return val.target_project_id === va.target_project_id && val.projectCloneDownload;
      });
      return !flag;
    });
    // 后端让减少发送请求的次数，ops顶不住
    const allRequest =
      cloneArray &&
      cloneArray.length > 0 &&
      cloneArray.map(async (va) => {
        const questValue = await getCloneDownloadSetting(va.target_project_id);
        return questValue;
      });
    const result = await Promise.all(allRequest);
    const newList = cloneArray.map((va, idx) => {
      return { ...va, projectCloneDownload: result[idx] };
    });
    const dispatchValue = value.map((va) => {
      if (va.projectCloneDownload) {
        return { ...va };
      } else {
        const values = newList.find((val) => val.target_project_id === va.target_project_id);
        return {
          ...va,
          projectCloneDownload: values ? values.projectCloneDownload : projectClone(value, va),
        };
      }
    });
    dispatch({
      type: COVER_LIST_DATA,
      data: dispatchValue,
    });
  };
};

const getCloneDownloadSetting = (data) => {
  return exceed.forceFetch({
    api: 'project.clone_download',
    params: {
      projectId: data,
    },
  });
};

const projectClone = (data, type) => {
  const value = data.find((va) => {
    return va.target_project_id === type.target_project_id;
  });
  return value ? value.projectCloneDownload : '';
};

export function getTotalData(formData) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'mr.state_count',
        data: formData,
      })
      .then((list) => {
        dispatch({
          type: RECEIVE_TOTAL_DATA,
          data: list,
        });
      })
      .fail(console.log);
  };
}

export function setNavKey(data) {
  return (dispatch) => {
    dispatch({
      type: SET_NAV_KEY,
      data,
    });
  };
}

export function setSearchValue(data) {
  return (dispatch) => {
    dispatch({
      type: SET_SEARCH_VALUE,
      data,
    });
  };
}

export function setTabKey(data) {
  return (dispatch) => {
    dispatch({
      type: SET_TAB_KEY,
      data,
    });

    // dispatch(setResetList());
  };
}

export function setOrderKey(data) {
  return (dispatch) => {
    dispatch({
      type: SET_ORDER_KEY,
      data,
    });

    dispatch(setResetList());
  };
}

export function setSearch(data) {
  return (dispatch) => {
    dispatch({
      type: SET_SEARCH,
      data,
    });

    dispatch(setResetList());
  };
}

export function setResetList() {
  return (dispatch) => {
    dispatch({
      type: SET_RESET_LIST,
    });

    dispatch(getMergeRequests(1));
  };
}

export function setAdvancedSearch(data, onlySave) {
  return (dispatch) => {
    dispatch({
      type: SET_ADVANCEDSEARCHDATA,
      data,
    });

    !onlySave && dispatch(getAdvancedData(1));
  };
}

// 白名单设置
export const getIpWhite = () => {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'organization.ip_setting',
        params: {
          id: organization.id,
        },
      })
      .then((result) => {
        dispatch({
          type: GET_IP_WHITE,
          data: result,
        });
      });
  };
};
